package com.zgc.util;

import com.zgc.cache.ConnectionInfoCache;
import com.zgc.constant.ZkConstant;
import com.zgc.zkinfo.ZkConnectionInfo;
import javafx.collections.MapChangeListener;

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

public class LocalDataUtil {

    /**
     * 连接信息序列化
     */
    public static void connectInfoWriteLocal() {
        JsonUtil.Object2File(ConnectionInfoCache.zkConnectMap().values().toArray(ZkConnectionInfo[]::new), ZkConstant.CONNECT_FILE_PATH, ZkConstant.CONNECT_FILE_NAME);
    }

    /**
     * 连接信息反序列化
     */
    public static void connectInfoReaderLocal() {
        ZkConnectionInfo[] info = JsonUtil.file2Object(ZkConnectionInfo[].class, "/data", ZkConstant.CONNECT_FILE_NAME);
        if (info != null) {
            Map<String, ZkConnectionInfo> collect = Arrays.stream(info).collect(Collectors.toMap(ZkConnectionInfo::getId, zkConnectionInfo -> zkConnectionInfo));
            ConnectionInfoCache.putAllConnectInfo(collect);
        }
    }

    public static void connectInfoWatch() {
        ConnectionInfoCache.zkConnectMap().addListener((MapChangeListener<String, ZkConnectionInfo>) change -> connectInfoWriteLocal());
    }


}
